from HTMLParser import HTMLParser

class Parser(HTMLParser):
    def __init__(self,li):
        self.area=li
        self.area_idx=""
        self.newthread={}
        self.newpost={}
        self.pending='start'
        HTMLParser.__init__(self)

    def handle_starttag(self,tag,attrs):
        if tag=="a":
            for attr in attrs:
                if attr[0]=='href':
                    for item in self.area:
                        if 'Board='+item in attr[1].split('&'):
                            if self.pending!='start':
                                self.pending='start'
                            self.area_idx=item
                            self.pending='area_found'
                            

        if (tag=="td") :
            if (self.pending in ['area_found','threadnew','postnew']):
                for attr in attrs:
                    if (attr[0]=='class') and (attr[1]=='threadtotal'):
                        self.pending='threadnew'
                    elif (attr[0]=='class') and (attr[1]=='posttotal'):
                        self.pending='postnew'
                
        if (tag=='font') and (self.pending !='start'):
            for attr in attrs:
                if (attr[0]=='class') and (attr[1]=='new'):
                    if self.pending=='threadnew':
                        self.pending='threaddata'
                    elif self.pending=='postnew':
                        self.pending='postdata'
        if (tag=='tr'):
            for attr in attrs:
                if (attr[0]=='class') and (attr[1]=='darktable'):
                    self.pending='start'
    
    def handle_data(self,data):
        if self.pending=='threaddata':
            self.newthread[self.area_idx]=data[1:-4]
            self.pending='postnew'
        elif self.pending=='postdata':
            self.newpost[self.area_idx]=data[1:-4]
            self.pending='start'

    def output(self):
        for item in self.area:
            if not self.newpost.has_key(item):
                self.newpost[item]='0'
            if not self.newthread.has_key(item):
                self.newthread[item]='0'
        print "new post :",self.newpost
        print "new thread :",self.newthread


def feed(htm,li):
    if len(li)==0:
        return {},{}
    tp=Parser(li)
    tp.feed(htm)
    for item in li:
        if not tp.newpost.has_key(item):
            tp.newpost[item]='0'
        if not tp.newthread.has_key(item):
            tp.newthread[item]='0'
    #tp.output()
    return tp.newpost,tp.newthread

